/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.inv.input.controller;

import java.math.BigDecimal;
import java.util.*;

import javax.validation.Valid;

import com.erp.inv.input.dao.model.*;
import com.erp.inv.input.service.InvInputHeadService;
import com.erp.masterdata.common.param.MasterDataParam;
import com.erp.masterdata.material.dao.data.DataBox;
import com.erp.order.dn.dao.model.DeliveryNoteLine;
import com.erp.order.dn.dao.model.DeliveryNoteLineCO;
import com.erp.order.dn.service.DeliveryNoteLineService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.inv.input.service.InvInputLineService;
import com.erp.inv.inputeco.dao.model.InvInputLineM;
import com.erp.inv.inputeco.service.InputEcoService;
import com.erp.inv.inputeco.service.InvInputLineMService;
import com.erp.inv.output.dao.model.ProdInvOutputLine;
import com.erp.inv.output.service.InvOutputLineService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.material.dao.model.MdMaterial;
import com.erp.order.po.dao.model.PoLine;
import com.erp.order.po.dao.model.PoLineCO;
import com.erp.order.po.service.PoLineService;
import com.erp.prod.wip.service.ProdWipTaskMaterialService;

@Controller
@RequestMapping("/web/invInputLine")
public class InvInputLineWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(InvInputLineWebController.class);
    
    //服务层注入
    @Autowired
    private InvInputLineService invInputLineService;
    @Autowired
    private InvInputHeadService invInputHeadService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private PoLineService poLineService;
    @Autowired
    private InvInputLineMService invInputLineMService;
    @Autowired
    private InputEcoService inputEcoService;
    @Autowired
    private ProdWipTaskMaterialService prodWipTaskMaterialService;
    @Autowired
    private InvOutputLineService invOutputLineService;
    @Autowired
    private DeliveryNoteLineService deliveryNoteLineService;
    
    
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getInvInputLineList");
    }


    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-08-20 17:21:44
     * @author 
     * @param pages
     * @param invInputLineVO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputLineList")
    @ResponseBody
    public Object getInvInputLineList(Pages pages, InvInputLineVO invInputLineVO, String supply_material_id, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);


        /**
         * 根据supply_material_detail与md_material 连查
         * 获取物料信息等
         * 所传查询参数为supply_material_id
         * */


        //supply_material_id = "20200001";
        //supply_material_id = "";
        List<InvInputLineVO> invInputLineList =
                invInputLineService.getInputLineAndMaterial(pages,invInputLineVO,supply_material_id);

        for(int i = 0; i < invInputLineList.size(); i++){

            BigDecimal a = new BigDecimal(invInputLineList.get(i).getNum());
            BigDecimal b = new BigDecimal(invInputLineList.get(i).getPrice());


            BigDecimal multiplyVal = a.multiply(b);


            invInputLineList.get(i).setAllPrice(multiplyVal.toString());
            invInputLineList.get(i).setLoss("0");
            invInputLineList.get(i).setGive("0");
            invInputLineList.get(i).setAttached_memo("");


            Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
            String ewr = invInputLineList.get(i).getStandard_unit();
            String sdf = materialUnitMap.get(ewr).toString();
            invInputLineList.get(i).setStandard_unit(sdf);

        }




      /*  //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //分页查询数据
        List<InvInputLineBase> invInputLineList = new ArrayList<InvInputLineBase>();
        //根据version请求参数，判断数据从原表获取还是变更表获取
        if(invInputLineCO.getVersion()!=null&&invInputLineCO.getVersion()>0) {
            InvInputLineM invInputLineM = new InvInputLineM();
            invInputLineM.setInputHeadCode(invInputLineCO.getInputHeadCode());
            invInputLineM.setVersion(invInputLineCO.getVersion());
            List<InvInputLineM> list = this.invInputLineMService.getDataObjects(pages, invInputLineM);
            for(InvInputLineM obj: list) {
                invInputLineList.add(obj);
            }
        }else {
            List<InvInputLine> list = this.invInputLineService.getInvInputLineListByInputHeadCode(pages, invInputLineCO);
            for(InvInputLine obj: list) {
                invInputLineList.add(obj);
            }
        }
        
        for(InvInputLineBase invInputLine: invInputLineList) {
            invInputLine.setMaterialName(materialMap.get(invInputLine.getMaterialCode()).toString());
            invInputLine.setPoUnit(materialUnitMap.get(invInputLine.getUnit()).toString());
            //获取物料规格
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(invInputLine.getMaterialCode());
            invInputLine.setMaterialStandard(mdMaterial.getStandard());
        }*/
        
        //页面属性设置invInputLineList
       /* model.addAttribute("invInputLineList", invInputLineList);
        model.addAttribute("pages", pages);*/

        Map result = new Hashtable();
        result.put("invInputLineList",invInputLineList);
        result.put("code",0);
        //return "invInput/invInputEdit";
        return result;
    }
    
    
    
    /**
     * 
     * @description 获取采购订单行选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectPOLineModal")
    public String getSelectPOLineModal(Pages pages, PoLineCO poLineCO, InvInputLineCO invInputLineCO, InvInputHeadCO invInputHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(1000);
        
        //分页查询采购订单行数据
        List<PoLine> poLineList = this.poLineService.getPoLineListByPoHeadCode(pages, poLineCO);
        
        //订单行获取已入库的数量
        if(invInputHeadCO.getInputSourceType().equals("PO")) {
            List<Object[]> listTemp = this.inputEcoService.getPoLineInputQuantityByPoHead(poLineCO.getPoHeadCode());
            //循环设置采购订单入库数量
            for(PoLine poLine: poLineList) {
                //初始化入库数量
                poLine.setInputQuantity(BigDecimal.ZERO);
                for(int a=0;a<listTemp.size();a++) {
                    Object[] obj = listTemp.get(a);
                    if(poLine.getPoLineCode().equals(String.valueOf(obj[0]))) {
                        poLine.setInputQuantity(new BigDecimal(String.valueOf(obj[1])));
                        break;
                    }
                }
            }
        }
        
        //获取入库行数据
        Pages pagesTemp = new Pages();
        pagesTemp.setPage(1);
        pagesTemp.setMax(100);
        List<InvInputLine> invInputLineList = this.invInputLineService.getInvInputLineListByInputHeadCode(pagesTemp, invInputLineCO);
        
        //剔除已经做了入库行的采购订单行
        Iterator<PoLine> poLineIt = poLineList.iterator();
        while(poLineIt.hasNext()) {
            PoLine poLineTemp = poLineIt.next();
            
            //剔除非物料的采购订单行
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(poLineTemp.getMaterialCode());
            if(mdMaterial!=null&&mdMaterial.getMaterialType().equals("MATTER")) {
                poLineIt.remove();
            }
            
            //判断当前入库行是否存在此物料
            for(InvInputLine invInputLineTemp: invInputLineList) {
                if(poLineTemp.getPoLineCode().equals(invInputLineTemp.getInputSourceLineCode())) {
                    poLineIt.remove();
                    break;
                }
            }
        }
        //重置总数据数量
        pages.setDataNumber(poLineList.size());
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //页面属性设置
        model.addAttribute("poLineList", poLineList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        
        return "invInput/pop/selectPOLineModal";
    }

    /**
     *
     * @description 获取采购订单行选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectDeliveryNoteModal")
    public String getSelectDeliveryNoteModal(Pages pages, DeliveryNoteLineCO deliveryNoteLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        deliveryNoteLineCO.setStatus(MasterDataParam.DELIVERY_STATUS_N);
        deliveryNoteLineCO.setIsDel(MasterDataParam.IS_DEL_NO);
        //分页查询发货单行数据
        //获取入库行数据
        pages.setMax(100);
        List<DeliveryNoteLine> noteLineList = this.deliveryNoteLineService.getDataObjects(pages, deliveryNoteLineCO);

        //重置总数据数量
        pages.setDataNumber(noteLineList.size());
        //页面属性设置
        model.addAttribute("noteLineList", noteLineList);
        model.addAttribute("pages", pages);

        return "invInput/pop/selectDeliveryNoteLineModal";
    }
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-08-20 17:21:44
     * @author 
     * @param invInputLine
     * @param model
     * @return String
     *
     */
    @RequestMapping("getInvInputLine")
    public String getInvInputLine(InvInputLine invInputLine, String inputType, String inputSourceType, String inputSourceHeadCode, Model model) {
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        //生产任务物料需求数量
        Map prodMaterialQuantityMap = new HashMap<String, Double>();
        //生产任务物料需求行编码
        Map prodTaskMaterialLineMap = new HashMap<String, String>();
        
        //查询要编辑的数据
        if(invInputLine!=null&&invInputLine.getInputLineId()!=null) {
            invInputLine = this.invInputLineService.getDataObject(invInputLine.getInputLineId());
            //根据来源获取单据数据
            if(StringUtils.isNotBlank(inputSourceType)) {
                DeliveryNoteLine noteLine = deliveryNoteLineService.getDataObject(Integer.valueOf(invInputLine.getInputSourceLineCode()));
                if(ObjectUtils.isNotEmpty(noteLine)){
                    invInputLine.setMaterialName(noteLine.getMaterialName());
                    invInputLine.setMaterialStandard(noteLine.getStandard());
                }
            }
        }
        model.addAttribute("typeMap", datasetCommonService.getDictByKey("material_unit"));
        //获取主表状态
        InvInputHead invInputHead = invInputHeadService.getDataByCode(invInputLine.getInputHeadCode());

        //页面属性设置
        model.addAttribute("approveStatus", ObjectUtils.isNotEmpty(invInputHead) ? invInputHead.getApproveStatus() : null);
        model.addAttribute("isReportMap", DataBox.getIsReportMap());
        model.addAttribute("invMeansMap", DataBox.getInvMeansMap());
        model.addAttribute("invInputLine", invInputLine);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("materialUnitMap", materialUnitMap);

        return "invInput/pop/addLineModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-08-20 17:21:44
     * @author 
     * @param invInputLine
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editInvInputLine")
    @ResponseBody
    public String editInvInputLine(@Valid InvInputLine invInputLine, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            /*
            //参数校验
            Map<String, String> errorMap = this.validateParameters(bindingResult, model);
            if(errorMap.size()>0) {
                return "forward:getInvInputLine";
            }
            */
            
            //对当前编辑的对象初始化默认的字段
            if(invInputLine.getInputLineId()==null) {
                invInputLine.setInputLineCode(SnowFlake.getConcurrentId().toString());
            }
            //将发货单状态改为已入库

            DeliveryNoteLine deliveryNoteLine = deliveryNoteLineService.getDataObject(Integer.valueOf(invInputLine.getInputSourceLineCode()));
            deliveryNoteLine.setStatus(MasterDataParam.DELIVERY_STATUS_Y);
            deliveryNoteLineService.insertOrUpdateDataObject(deliveryNoteLine);
//            保存编辑的数据
            this.invInputLineService.insertOrUpdateDataObject(invInputLine);

            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-08-20 17:21:44
     * @author 
     * @param invInputLine
     * @return String
     *
     */
    @RequestMapping("deleteInvInputLine")
    @ResponseBody
    public String deleteInvInputLine(InvInputLine invInputLine, RedirectAttributes attr) {
        try {
            //删除数据前验证数据
            if(invInputLine!=null&&invInputLine.getInputLineId()!=null) {
                //删除数据
                this.invInputLineService.deleteDataObject(invInputLine);
            }
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
}
